<?php

namespace app\index\controller;
use think\Cache;
use think\Session;
use think\Db;


class Login {

    // 发送注册短信
    //url 
    public function sendSms() {
        $phone = input('param.phone');
        $type = input('param.type'); // 1注册，2修改密码
        if ($type == 1) {
            $tmpId = 379675;
        } else {
            $tmpId = 379555;
        }
            $num = rand(1001, 9999);
            Cache::set($phone, $num, 300);
            $data = sendTemplateSMS($phone, [$num], $tmpId);
            if ($data == null || $data->statusCode != 0) {
                return ['data' => [], 'code' => 1002, 'message' => '发送失败'];
            } else {
                return ['data' => ['num' => $num], 'code' => 1000, 'message' => '操作完成'];
            }
        
    }

    /**
     * 用户登录注册
     */
    public function login() {
        $phone =  input('param.phone');// 手机号码
        $code_num =  input('param.code');//验证码
        $open_type =  input('param.app_flag');//app_flag
        $user_uid_parent =  input('param.user_uid_parent');
       
        $cache_code = Cache::get($phone);
        if(!$cache_code){
            return retData([],'1001','验证码过期');
        }else {
          if($code_num!='' && $code_num == $cache_code){ //验证码有效
            $userinfo = Db::name('chat_userinfo')->where(['user_phone' => $phone])->find();
            if($userinfo){
               Session::set('user_id',$userinfo['user_id']);
               Session::set('user_uid',$userinfo['user_uid']);
               Session::set('userinfo',$userinfo);
               return retData($userinfo,'1000','登录成功');
            }else{//新用户注册
                $membernum = Db::name('chat_userinfo')->max('user_id') ?? '1000';
                
                $insert = [
                    'user_id' => $membernum +1,
                    'user_uid' => $open_type.md5($membernum +1),
                    'user_uid_parent' => $user_uid_parent,
                    'user_name' => $phone.'_'. rand(1000, 9999),
                    'user_phone' => $phone,
                    'open_type' => $open_type,
                ];
                if(Db::name('chat_userinfo')->insert($insert)){ 
                    
                    //开通钱包
                     $map = [
                        'user_uid' => input('param.user_uid'),
                        'app_flag' => input('param.app_flag'),
                    ];
                     Db::table($this->table)->insert($map);
                                        
                     Session::set('user_id',$insert['user_id']);
                     Session::set('user_uid',$insert['user_uid']);
                     Session::set('user_uid',$insert['user_uid']);
                     Session::set('app_flag',$open_type);
                     return retData([],'1000','注册成功');
                }else {
                     return retData([],'1002','注册失败');
                }
            }
         }  
        }
        
    }


}
